<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * I18n library
 */
class I18n {
	private static $_instance = null;
	private $_container = array();

	public static function &instance() {
		if (!isset(self::$_instance)) {
			$c = __CLASS__;
			self::$_instance = new $c;
		}

		return self::$_instance;
	}

	public function __clone() {
		throw new Node_Exception('Can`t clone singletone object');
	}

	private function __construct() {
		$default = Config::get('default', 'i18n');
		$current = Router::getLanguage();

		$this->_load($default);

		if ($default != $current) {
			$this->_load($current);
		}
	}

	/**
	 * Loading language
	 */
	private function _load($lang_code) {
		$paths = Node::findFile('i18n', $lang_code);
		foreach ($paths as $path) {
			$i18n_arr = include($path);
			$this->_container = array_merge($this->_container, $i18n_arr);
		}
	}

	/**
	 * Get value
	 */
	public static function get($str, $vars = array()) {
		$result = $str;
		$i18n = self::instance();

		if (isset($i18n->_container[$str])) {
			$result = $i18n->_container[$str];
		}

		if (!empty($vars)) {
			$result = self::parse($result, $vars);
		}

		return $result;
	}

	/**
	 * Get value
	 */
	public static function set($offset, $value) {
		self::instance()->_container[$offset] = $value;
	}

	/**
	 * Factory value
	 */
	public static function parse($str, $vars = array(), $start_tag = '{%', $end_tag = '%}') {
		if (!empty($vars)) {
			foreach ($vars as $key => $val) {
				$var_str = $start_tag . $key . $end_tag;
				$str = str_replace($var_str, $val, $str);
			}
		}
		return $str;
	}

	/**
	 * Output all config values
	 */
	public static function dump() {
		print_r(self::instance()->_container);
	}
}
